package cn.dankal.flyaudio.home

import android.graphics.Bitmap
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory
import androidx.recyclerview.widget.GridLayoutManager
import cn.dankal.basiclib.DKUserManager
import cn.dankal.basiclib.DankalApplication
import cn.dankal.basiclib.GlideApp
import cn.dankal.basiclib.base.callback.DKCallBackObject
import cn.dankal.basiclib.base.recyclerview.BaseRecyclerViewAdapter
import cn.dankal.basiclib.base.recyclerview.BaseRecyclerViewHolder
import cn.dankal.basiclib.protocol.MainProtocol
import cn.dankal.basiclib.util.TimeUtil
import cn.dankal.basiclib.util.image.PicUtils
import cn.dankal.basiclib.widget.CommonDialog
import cn.dankal.business.Constants
import cn.dankal.business.pojo.CurrentBean
import cn.dankal.flyaudio.R
import cn.dankal.flyaudio.adapter.CurrentImgsAdapter
import cn.dankal.flyaudio.view.RecyclerViewCornerRadius
import cn.dankal.flyaudio.view.RecyclerViewSpacesItemDecoration
import com.alibaba.android.arouter.launcher.ARouter
import com.bear.screenshot.utils.dip2px
import com.bumptech.glide.request.target.BitmapImageViewTarget
import kotlinx.android.synthetic.main.item_current.view.*
import kotlinx.android.synthetic.main.rv_item_current.view.fl_cover
import kotlinx.android.synthetic.main.rv_item_current.view.iv_user
import kotlinx.android.synthetic.main.rv_item_current.view.iv_video_play
import kotlinx.android.synthetic.main.rv_item_current.view.tv_comment_count
import kotlinx.android.synthetic.main.rv_item_current.view.tv_delete_content
import kotlinx.android.synthetic.main.rv_item_current.view.tv_name
import kotlinx.android.synthetic.main.rv_item_current.view.tv_praise_count
import kotlinx.android.synthetic.main.rv_item_current.view.tv_time
import kotlinx.android.synthetic.main.rv_item_current.view.tv_title
import java.util.*


class CurrentAdapter(val callBack: DKCallBackObject<String>) : BaseRecyclerViewAdapter<CurrentBean>() {

    private lateinit var praiseListener: OnPraiseListener
    fun setOnParseListener(pariseListener: OnPraiseListener) {
        praiseListener = pariseListener
    }

    override fun getLayoutResId(viewType: Int): Int {
        return R.layout.item_current
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getViewHolder(parent: ViewGroup?, rootView: View, viewType: Int): BaseRecyclerViewHolder<*> {

        return CurrentViewHolder(rootView, callBack, praiseListener)
    }

    override fun onBindViewHolder(holder: BaseRecyclerViewHolder<CurrentBean>, position: Int, payloads: MutableList<Any>) {
        if (payloads.isEmpty()) {
            super.onBindViewHolder(holder, position, payloads)
            return
        }

        var currentBena: CurrentBean = findData(position)

        var itemView = holder.findViewById<TextView>(R.id.tv_praise_count)
        for (item in payloads) {
            if ("star".equals(item.toString())) {
                currentBena?.run {
                    itemView.tv_praise_count.text = likeNumber
                    if (isPraise > 0) {
                        val drawable = context.getResources().getDrawable(R.mipmap.ic_zan_selected)
                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight())//必须设置图片大小，否则不显示
                        itemView.tv_praise_count.setCompoundDrawables(drawable, null, null, null)
                    } else {
                        val drawable = context.getResources().getDrawable(R.mipmap.icon_zan)
                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight())//必须设置图片大小，否则不显示
                        itemView.tv_praise_count.setCompoundDrawables(drawable, null, null, null)
                    }
                }
            }
        }
    }

    class CurrentViewHolder(itemView: View?, val callBack: DKCallBackObject<String>, val praiseListener: OnPraiseListener) : BaseRecyclerViewHolder<CurrentBean>(itemView) {

        // 上次点赞的时间
        private var lastPraiseTime = 0L

        // 上次点赞的UUID
        private var lastPraiseUUID: String = ""

        // 暴力点击的阻隔时间 单位：ms
        private var barrierTime = 1200L


        override fun onBindData(data: CurrentBean?, position: Int) {
            data?.run {
                GlideApp.with(DankalApplication.getContext()).asBitmap().centerCrop().error(R.mipmap.pic_ill_4).load(PicUtils.getUrl(avatar)).into(object : BitmapImageViewTarget(itemView.iv_user) {
                    override fun setResource(resource: Bitmap?) {
                        val circularBitmapDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), resource)
                        circularBitmapDrawable.isCircular = true
                        itemView.iv_user.setImageDrawable(circularBitmapDrawable)
                    }
                })

                if (list == null || list.isEmpty()) {
                    itemView.fl_cover.visibility = View.GONE
                } else {
                    itemView.fl_cover.visibility = View.VISIBLE
                    itemView.recyclerview.layoutManager = GridLayoutManager(context, 3)
                    val adapter = CurrentImgsAdapter();
                    val stringIntegerHashMap = HashMap<String, Int>()
                    stringIntegerHashMap[RecyclerViewSpacesItemDecoration.LEFT_DECORATION] = 3//左间距
//                    val radiusItemDecoration = RecyclerViewCornerRadius(itemView.recyclerview)
//                    radiusItemDecoration.setCornerRadius(dip2px(context,4f))
//                    itemView.recyclerview.addItemDecoration(radiusItemDecoration)
//
                    itemView.recyclerview.addItemDecoration(RecyclerViewSpacesItemDecoration(stringIntegerHashMap))
                    itemView.recyclerview.adapter = adapter
                    if (list.size > 3) {
                        adapter.addDatas(list.subList(0, 3), true)
                    } else {
                        adapter.addDatas(list, true)
                    }
//                    PicUtils.loadNormal(list[0], itemView.iv_img)
                }
                itemView.content.setOnClickListener {
                    ARouter.getInstance().build(MainProtocol.CURRENT_DETAIL)
                            .withString(Constants.UUID, data.uuid)
                            .navigation()
                }
                itemView.iv_video_play.visibility = if (("2").equals(type)) View.VISIBLE else View.GONE
                itemView.tv_title.text = content
                itemView.tv_name.text = name
                itemView.tv_time.text = TimeUtil.friendly_time(TimeUtil.date2TimeStampLong(createTime, TimeUtil.DATEFORMATER, true))
                itemView.tv_comment_count.text = commentNumber
                itemView.tv_praise_count.text = likeNumber
//                itemView.tv_fans.text = data.likeNumber;
                if (isPraise > 0) {
                    val drawable = context.getResources().getDrawable(R.mipmap.ic_zan_selected)
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight())//必须设置图片大小，否则不显示
                    itemView.tv_praise_count.setCompoundDrawables(drawable, null, null, null)
                } else {
                    val drawable = context.getResources().getDrawable(R.mipmap.icon_zan)
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight())//必须设置图片大小，否则不显示
                    itemView.tv_praise_count.setCompoundDrawables(drawable, null, null, null)
                }
                //点赞
                itemView.tv_praise_count.setOnClickListener {
                    // 防止暴力点击 防止相同的位置重复点击
                    if (lastPraiseTime + barrierTime > System.currentTimeMillis()) {
                        lastPraiseTime = System.currentTimeMillis()
                        return@setOnClickListener
                    } else {
                        lastPraiseTime = System.currentTimeMillis()
                        lastPraiseUUID = uuid
                    }

                    if (data.isPraise > 0) {
                        praiseListener?.praiseCancel(uuid, data.type, position)
                    } else {
                        praiseListener?.praise(uuid, data?.type, position)
                    }
                }


                lateinit var commonDialog: CommonDialog

                if (userUuid.equals(DKUserManager.getUserInfo().userUuid)) {
                    itemView.tv_delete_content.visibility = View.VISIBLE
                } else {
                    itemView.tv_delete_content.visibility = View.GONE
                }

                //删除
                itemView.tv_delete_content.setOnClickListener {
                    if (lastPraiseTime + barrierTime > System.currentTimeMillis()) {
                        lastPraiseTime = System.currentTimeMillis()
                        return@setOnClickListener
                    } else {
                        lastPraiseTime = System.currentTimeMillis()
                        lastPraiseUUID = uuid
                    }
                    val builder = CommonDialog.Builder(context)
                    builder.setTitle("是否确认删除该信息？")

                    builder.setNegativeButton("取消",
                            context.resources.getColor(R.color.color14)) {
                        commonDialog.dismiss()
                    }

                    builder.setPositiveButton("删除",
                            context.resources.getColor(R.color.colorPrimary)) {

                        var uuids = arrayOfNulls<String?>(1)
                        uuids[0] = uuid
                        praiseListener?.deleteDate(uuids, position)
                        commonDialog.dismiss()
                    }
                    commonDialog = builder.create()
                    commonDialog.show()

                }
            }
        }
    }

    interface OnPraiseListener {

        fun praise(uuid: String, type: String, position: Int)

        fun praiseCancel(uuid: String, type: String, position: Int)

        fun deleteDate(uuids: Any, position: Int)
    }

}
